<?php

namespace app\index\controller;

use app\index\model\Myorder;
use app\index\model\Cart;
use app\index\model\Shoplist;
use app\index\model\Book;
use think\Controller;
use think\Db;
use think\migration\command\migrate\Rollback;

class Forder extends Controller
{
    // 显示订单完成界面
    public function forder()
    {
        $orderID = input('get.orderID');
        $this->assign('orderID', $orderID);

        return $this->fetch();
    }

    // 添加一个订单
    public function addOrder()
    {
        // 开启一个事务
        Db::startTrans();
        try {
            //1、myOrder表
            $order = new Myorder();
            $order->email = session('email');
            $order->custID = input('post.custID');
            $order->shifu = input('post.shifu');
            $order->inputtime = date("Y-m-d H:i:s");
            $order->STATUS = '未付款';
            $order->cltime = $order->inputtime; //订单更新时间
            $order->save();

            //2、soplist、Cart
            $cartIDs = session('cartIDs');
            $carts = Cart::where('cartID', 'in', $cartIDs)->select();
            foreach ($carts as $cart) {
                // (2.3)新建shoplist表对象$shoplist
                $shoplist = new Shoplist();
                // (2.4)绑定orderID、email、flowerID、num属性属性
                $shoplist->orderID = $order->orderID;
                $shoplist->bookID = $cart->bookID;
                $shoplist->email = session('email');
                $shoplist->num = $cart->num;
                $shoplist->save();

                //3、Book
                $book = Book::get($cart->bookID);
                $book->SelledNum = $book->SelledNum + $cart->num;
                $book->storenum -= $cart->num;
                $book->save();

                $cart->delete(); //从购物车中删除
            }
            Db::commit(); 
            return $order->orderID;
        } catch (\Exception $e) {
            Db::rollback();
            return "error";
        }
    }
}
